class Student:
    """学生类，包含学生基本信息和成绩"""

    def __init__(self, name, student_id):
        self.name = name
        self.student_id = student_id
        self.scores = {}  # 存储科目和对应的成绩

    def add_score(self, subject, score):
        """添加科目成绩"""
        self.scores[subject] = score

    def calculate_average(self):
        """计算平均分"""
        if not self.scores:
            return 0
        return sum(self.scores.values()) / len(self.scores)

    def get_highest_score(self):
        """获取最高分科目"""
        if not self.scores:
            return None, 0
        highest_subject = max(self.scores, key=self.scores.get)
        return highest_subject, self.scores[highest_subject]

    def display_info(self):
        """显示学生信息"""
        print(f"\n学生姓名: {self.name}")
        print(f"学号: {self.student_id}")
        print("各科成绩:")
        for subject, score in self.scores.items():
            print(f"  {subject}: {score}")
        print(f"平均分: {self.calculate_average():.2f}")
        highest_subject, highest_score = self.get_highest_score()
        print(f"最高分科目: {highest_subject} ({highest_score}分)")


class GradeManager:
    """成绩管理器类"""

    def __init__(self):
        self.students = []

    def add_student(self, student):
        """添加学生"""
        self.students.append(student)
        print(f"成功添加学生: {student.name}")

    def find_student_by_id(self, student_id):
        """根据学号查找学生"""
        for student in self.students:
            if student.student_id == student_id:
                return student
        return None

    def display_all_students(self):
        """显示所有学生信息"""
        if not self.students:
            print("\n暂无学生信息")
            return

        print("\n=== 所有学生信息 ===")
        for i, student in enumerate(self.students, 1):
            print(f"\n--- 学生 {i} ---")
            student.display_info()

    def get_class_average(self):
        """计算班级平均分"""
        if not self.students:
            return 0

        total_average = 0
        count = 0

        # 使用while循环计算
        i = 0
        while i < len(self.students):
            total_average += self.students[i].calculate_average()
            count += 1
            i += 1

        return total_average / count if count > 0 else 0


def main():
    """主函数"""
    manager = GradeManager()

    print("=== 学生成绩管理系统 ===")

    # 使用while循环创建菜单系统
    while True:
        print("\n请选择操作:")
        print("1. 添加学生")
        print("2. 添加成绩")
        print("3. 查看所有学生")
        print("4. 查找学生")
        print("5. 查看班级平均分")
        print("6. 退出系统")

        choice = input("请输入选择 (1-6): ")

        if choice == '1':
            # 添加学生
            name = input("请输入学生姓名: ")
            student_id = input("请输入学号: ")
            student = Student(name, student_id)
            manager.add_student(student)

        elif choice == '2':
            # 添加成绩
            student_id = input("请输入学号: ")
            student = manager.find_student_by_id(student_id)
            if student:
                subject = input("请输入科目名称: ")
                try:
                    score = float(input("请输入成绩: "))
                    student.add_score(subject, score)
                    print(f"成功为 {student.name} 添加 {subject} 成绩: {score}")
                except ValueError:
                    print("成绩必须是数字!")
            else:
                print("未找到该学号的学生!")

        elif choice == '3':
            # 查看所有学生
            manager.display_all_students()

        elif choice == '4':
            # 查找学生
            student_id = input("请输入要查找的学号: ")
            student = manager.find_student_by_id(student_id)
            if student:
                student.display_info()
            else:
                print("未找到该学生!")

        elif choice == '5':
            # 查看班级平均分
            class_avg = manager.get_class_average()
            print(f"\n班级平均分: {class_avg:.2f}")

        elif choice == '6':
            print("感谢使用学生成绩管理系统，再见!")
            break

        else:
            print("无效选择，请重新输入!")


# 演示代码功能
if __name__ == "__main__":
    # 创建一些示例数据
    manager = GradeManager()

    # 创建学生对象
    student1 = Student("张三", "2024001")
    student2 = Student("李四", "2024002")

    # 使用for循环批量添加成绩
    subjects_scores1 = [("数学", 85), ("英语", 92), ("物理", 78)]
    subjects_scores2 = [("数学", 88), ("英语", 85), ("物理", 90)]

    print("=== 批量添加成绩演示 ===")
    for subject, score in subjects_scores1:
        student1.add_score(subject, score)
        print(f"为 {student1.name} 添加 {subject}: {score}")

    for subject, score in subjects_scores2:
        student2.add_score(subject, score)
        print(f"为 {student2.name} 添加 {subject}: {score}")

    # 添加学生到管理器
    manager.add_student(student1)
    manager.add_student(student2)

    # 显示所有学生信息
    manager.display_all_students()

    # 计算班级平均分
    print(f"\n班级总平均分: {manager.get_class_average():.2f}")

    print("\n" + "=" * 50)
    print("现在启动交互式系统:")
    print("=" * 50)

    # 启动交互式系统
    main()